package com.bjpowernode.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.InvalidKeyException;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.lang3.time.DateUtils;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @description:
 * @author: panDeng_Zhu
 * @time: 2022/11/11 21:26
 */

public class JwtUtil {

    private String userKey ="";

    public JwtUtil(String userKey) {
        this.userKey = userKey;
    }

    //生成token
    public String createJwt(Map<String,Object> payLoad,int minute){
        String jwt =null;

        try {
            SecretKey secretKey = Keys.hmacShaKeyFor(userKey.getBytes(StandardCharsets.UTF_8));
            jwt= Jwts.builder().signWith(secretKey, SignatureAlgorithm.HS256)
            .setExpiration(DateUtils.addHours(new Date(),minute))
            .addClaims(payLoad).compact();
        } catch (InvalidKeyException e) {
            jwt =null;
            e.printStackTrace();
        }
        return jwt;
    }

    //读取token 验证是否有效
    public Claims readToken (String jwt)throws Exception{
        SecretKey secretKey =Keys.hmacShaKeyFor(userKey.getBytes(StandardCharsets.UTF_8));
        //1.获取Builder对象
        JwtParserBuilder builder = Jwts.parserBuilder();
        //2.获取key 和Parser
        JwtParser parser =builder.setSigningKey(secretKey).build();
        //4.解析数据
        Jws<Claims> claims =parser.parseClaimsJws(jwt);
        //5.获取数据
        Claims body =claims.getBody();
        return body;
    }

}
